#include "stdafx.h"
#include "uLaw.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#define ZEROTRAP    /* turn on the trap as per the MIL-STD */
#define BIAS 0x84   /* define the add-in bias for 16 bit samples */
#define CLIP 32635
int cexp_lut[256]         = 
{
	0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,
		4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
		5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
		5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
		6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
		6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
		6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
		6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
		7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
};



int dexp_lut[8] = {0,132,396,924,1980,4092,8316,16764};




unsigned char linear2ulaw( unsigned short sample)
{
	int sign, exponent, mantissa;
	unsigned char ulawbyte;
	sign = (sample >> 8) & 0x80;
	if (sign != 0)
		sample = -sample;
	if (sample > CLIP)
		sample = CLIP;
	sample = sample + BIAS;
	exponent = cexp_lut[(sample >> 7) & 0xFF];
	mantissa = (sample >> (exponent + 3)) & 0x0F;
	ulawbyte = ~(sign | (exponent << 4) | mantissa);
#ifdef ZEROTRAP
	if (ulawbyte == 0)
		ulawbyte = 0x02;
#endif
	return ulawbyte;
}

unsigned short ulaw2linear(unsigned char ulawbyte)
{
	int sign, exponent, mantissa, sample;
	ulawbyte = ~ulawbyte;
	sign = (ulawbyte & 0x80);
	exponent = (ulawbyte >> 4) & 0x07;
	mantissa = ulawbyte & 0x0F;
	sample = dexp_lut[exponent] + (mantissa << (exponent + 3));
	if (sign != 0)
		sample = -sample;
	return sample;
}


void linear2ulawBlock( unsigned short *Samplebuf,unsigned char *ulawbytebuf,int size)
{
	int sign, exponent, mantissa;
	int i;
	unsigned short sample;
	for(i=0;i<size;i++)
	{
		sample=*Samplebuf++;
		sign = (sample >> 8) & 0x80;
		if (sign != 0)
			sample = -sample;
		if (sample > CLIP)
			sample = CLIP;
		sample = sample + BIAS;
		exponent = cexp_lut[(sample >> 7) & 0xFF];
		mantissa = (sample >> (exponent + 3)) & 0x0F;
		*ulawbytebuf = ~(sign | (exponent << 4) | mantissa);
#ifdef ZEROTRAP
		if (*ulawbytebuf == 0)
			*ulawbytebuf = 0x02;
#endif
		ulawbytebuf++;
	}
}

void ulaw2linearBlock(unsigned char *ulawbytebuf,unsigned short *Samplebuf,int size)
{
	int sign, exponent, mantissa;
	int i;
	unsigned ulawbyte;
	for(i=0;i<size;i++)
	{
		ulawbyte=*ulawbytebuf++;
		ulawbyte = ~ulawbyte;
		sign = (ulawbyte & 0x80);
		exponent = (ulawbyte >> 4) & 0x07;
		mantissa = ulawbyte & 0x0F;
		*Samplebuf = dexp_lut[exponent] + (mantissa << (exponent + 3));
		if (sign != 0)
			*Samplebuf = -*Samplebuf;
		Samplebuf++;
	}
}